<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    var takeCharacters = function (s, k) {
      if (k === 0) return 0;
      let suf = new Array(3).fill(0);
      const n = s.length;
      // 1. 初始化，满足条件的最短后缀的起始位置 j
      let j = n - 1;
      for (; j >= 0; j--) {
        suf[code(s[j])]++;
        if (suf[0] >= k && suf[1] >= k && suf[2] >= k) {
          break;
        }
      }
      if (suf[0] < k || suf[1] < k || suf[2] < k) {
        return -1;
      }
      // 2. 枚举前缀的终点，后缀在满足条件的基础上，不断后移
      let ans = n - j;
      for (let i = 0; i < n; i++) {
        suf[code(s[i])]++;
        while (j < n && suf[code(s[j])] > k) {
          suf[code(s[j])]--;
          j++;
        }
        ans = Math.min(ans, i + 1 + n - j);
      }
      return ans;
    };

    function code(x) {
      return x.charCodeAt() - 'a'.charCodeAt();
    }
    console.log(takeCharacters("aabaaaacaabc", 2));
  </script>
</body>

</html>